﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System.Data;
using System.Data.SqlClient;

using Common;
namespace eMarketing
{
    partial class GroupManager : PortalModuleBase, IActionable
    {
        private int loc_UserID;

        data.userDataSetTableAdapters.tm_user_groupsTableAdapter userGroupTA = new data.userDataSetTableAdapters.tm_user_groupsTableAdapter();
        data.userDataSet.tm_user_groupsDataTable userGroupTbl = new data.userDataSet.tm_user_groupsDataTable();
        data.userDataSet.tm_user_groupsRow userGroupRow;

        data.userDataSetTableAdapters.tm_group_syscodesTableAdapter groupSyscodeTA = new data.userDataSetTableAdapters.tm_group_syscodesTableAdapter();
        data.userDataSet.tm_group_syscodesDataTable groupSyscodeTbl = new data.userDataSet.tm_group_syscodesDataTable();
        data.userDataSet.tm_group_syscodesRow groupSyscodeRow;

        data.userDataSetTableAdapters.tm_group_memberTableAdapter groupMemberTA = new data.userDataSetTableAdapters.tm_group_memberTableAdapter();
        data.userDataSet.tm_group_memberDataTable groupMemberTbl = new data.userDataSet.tm_group_memberDataTable();
        data.userDataSet.tm_group_memberRow groupMemberRow;

        ArrayList loc_arActivityCat = new ArrayList();
        ArrayList loc_arProductCat  = new ArrayList();
        int myGroupId = 0;


        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                btnDeleteMember.Attributes.Add("onclick", "javascript:return confirm('Xóa thành viên đã chọn ?')");
                btnDeleteGroup.Attributes.Add("onclick", "javascript:return confirm('Xóa nhóm và tất cả các thành viên trong nhóm ?')");
                lblMessage.Visible = false;
                //userGroupTA.Connection.ConnectionString = sysLibs.GetConnectionString;
                //groupSyscodeTA.Connection.ConnectionString = sysLibs.GetConnectionString;
                //groupMemberTA.Connection.ConnectionString = sysLibs.GetConnectionString;

                if (Request.QueryString.Get("groupId") != null)
                    int.TryParse(Request.QueryString.Get("groupId"), out myGroupId);
                       
                if (!Page.IsPostBack)
                {
                    sysLibs.LoadToDropdownList(ddlGroupType, "tm_emarketGroupType", "code", "description1");
                    sysLibs.LoadToDropdownList(ddlGroupTypeS, "tm_emarketGroupType", "code", "description1", DropdownListOptions.AddSelectAll);
                    loc_UserID = UserId;

                    #region treeview
             
                    tvProductCat.textFldName = "description1";
                    tvProductCat.valueFldName = "code";
                    tvProductCat.dataTableName = "tm_productCat";
                    tvProductCat.parentFldName = "parentcode";

                    //set grouplist width
                    tm_GroupList_MemberList.MyWidth = 200;
                    tm_GroupList_MemberList.MyHeight = 100;
                    #endregion treeview
 
                    if (Session["SearchedData"] != null)
                        Session.Remove("SearchedData");

                    if (myGroupId > 0)
                        GetMemberByGroup(myGroupId);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }

        }


        #region Optional Interfaces

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Registers the module actions required for interfacing with the portal framework
        /// </summary>
        /// <value></value>
        /// <returns></returns>
        /// <remarks></remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        #endregion


        //OK1
        private bool ValidateAddGroup()
        {
            bool rs = true;

            string groupCode = txtGroupName.Text.Trim();
            if (groupCode == "" || !sysLibs.CheckStringSecurity(groupCode))
                rs = false;

            if (!sysLibs.CheckStringSecurity(txtGroupDescription.Text.Trim()))
                rs = false;

            if (groupCode.IndexOf(" ") >= 0)
            {
                rs = false;
                sysLibs.ShowNotice(lblMessage, "Tên nhóm không được có khoảng trắng.", true);
            }

            if (groupCode.Length < 15)
            {
                rs = false;
                sysLibs.ShowNotice(lblMessage, "Tên nhóm không được ngắn hơn 15 ký tự.", true);
            }

            rs = ValidateIsNotHasGroupCode();

            return rs;
        }

        //OK1
        private bool ValidateIsNotHasGroupCode()
        {
            bool rs = true;
            try
            {
                string groupCode = txtGroupName.Text.Trim();
                userGroupTbl = userGroupTA.GetDataByGroupCode(groupCode);
                if (userGroupTbl.Rows.Count > 0)
                    rs = false;

                if (rs == false)
                    sysLibs.ShowNotice(lblMessage, "Đã có tên nhóm này trong dữ liệu.", true);
            }
            catch (Exception exc)
            {
                string mess = exc.Message;
            }
            return rs;
        }

        //OK1
        private int GetGroupIDByGroupCode(string groupCode)
        {
            int groupID = 0;

            try
            {
                userGroupTbl = userGroupTA.GetDataByGroupCode(groupCode);
                if (userGroupTbl.Rows.Count > 0)
                    int.TryParse(userGroupTbl.Rows[0]["groupID"].ToString(), out groupID);
            }
            catch (Exception exc)
            {
                string mess = exc.Message;
            }
            return groupID;
        }

        //OK1
        private bool AddGroup()
        {
            bool result = true;

            try
            {
                userGroupRow = userGroupTbl.Newtm_user_groupsRow();
                userGroupRow.createOn = DateTime.Now;
                userGroupRow.description = txtGroupDescription.Text.Trim();
                userGroupRow.groupCode = txtGroupName.Text.Trim();
                userGroupRow.groupType = ddlGroupType.SelectedValue;

                if (ckSendToBuyer.Checked)
                    userGroupRow.sendToBuyer = true;
                else
                    userGroupRow.sendToBuyer = false;
                
                if(ckSendToSeller.Checked)
                    userGroupRow.sendToSeller = true;
                else
                    userGroupRow.sendToSeller = false;
                
                if(ckSendToVendor.Checked)
                    userGroupRow.sendToVendor = true;
                else
                    userGroupRow.sendToVendor = false;
           
                userGroupRow.status = "";
                userGroupRow.userId = UserId;
           
                userGroupTbl.Addtm_user_groupsRow(userGroupRow);
                userGroupTA.Update(userGroupTbl);
           
                if (result)
                {
                    //add tm_group_syscode
                    int groupID = GetGroupIDByGroupCode(txtGroupName.Text.Trim());
                    ArrayList arSelectedNodes = sysLibs.Translate(tvProductCat.GetSelectedNodes(), "tm_productCat", "code", "syscodeId");
                    if (arSelectedNodes != null)
                    {
                        for (int idx = 0;idx < arSelectedNodes.Count;idx++)
                        {
                            groupSyscodeTbl.Rows.Clear();
                            groupSyscodeRow = groupSyscodeTbl.Newtm_group_syscodesRow();
                            groupSyscodeRow.groupId = groupID;
                            groupSyscodeRow.syscodeId = int.Parse(arSelectedNodes[idx].ToString());
                            groupSyscodeTbl.Addtm_group_syscodesRow(groupSyscodeRow);
                            groupSyscodeTA.Update(groupSyscodeTbl);
                        }
                    }
                }
                
            }
            catch (Exception exc)
            {
                string mess = exc.Message;
                result = false;
            }
            return result;
        }
      
        //OK1
        private string BuiltSearchGroupQueryString()
        {
            string SQLCmd = "";
            try
            {
                string GroupName = tbxGroupName.Text.Trim();
                string Description = tbxDescription.Text.Trim();
                string GroupType = ddlGroupTypeS.SelectedValue.Trim();

                SQLCmd = " SELECT a.groupId, b.description1 as groupType, a.groupCode as groupName, a.description, a.createOn " +
                         " FROM tm_user_groups a INNER JOIN tm_emarketGroupType b ON a.groupType = b.code ";

                string SQLCond = "";
                if (GroupName != "")
                    if (cbxGroupName.Checked)
                        SQLCond += " (a.groupCode = N'" + GroupName + "')";
                    else
                        SQLCond += " (a.groupCode like N'" + Common.consts.constSQLAllWildcard + GroupName + Common.consts.constSQLAllWildcard + "')";

                if (Description != "")
                    SQLCond += (SQLCond != "" ? " AND " : "") + " (a.description LIKE N'" + Common.consts.constSQLAllWildcard + Description + Common.consts.constSQLAllWildcard + "')";

                if (GroupType != consts.constCbAllItemValue)
                    SQLCond += (SQLCond != "" ? " AND " : "") + "(a.groupType = '" + GroupType + "')";

                SQLCmd += (SQLCond != "") ? (" WHERE " + SQLCond) : "";
                return SQLCmd;
            }
            catch(Exception exc)
            {
                string mess = exc.Message;
            }
            return SQLCmd;
        }

        //OK1
        private void SearchGroup()
        {
            try
            {
                string strQuery = BuiltSearchGroupQueryString();

                dsGroupList.ConnectionString = sysLibs.GetConnectionString;
                dsGroupList.SelectCommand = strQuery;
                dsGroupList.Select(DataSourceSelectArguments.Empty);
            }
            catch(Exception exc)
            {
                string mess = exc.Message;
            }
        }

        //OK1
        private bool DeleteSelectedGroups()
        {
            bool result = false;
            try
            {
                for (int i = 0; i < gvGroupList.Rows.Count; i++)
                {
                    CheckBox ck = (CheckBox)gvGroupList.Rows[i].FindControl("ck");
                    if (ck.Checked)
                    {
                        Label lblGroupId = (Label)gvGroupList.Rows[i].FindControl("lblGroupId");
                        int groupId = 0; int.TryParse(lblGroupId.Text, out groupId);
                        if (groupId > 0)
                        {
                            groupSyscodeTA.DeleteByGroupId(groupId);
                            groupMemberTA.DeleteByGroupId(groupId);
                            userGroupTA.Delete(groupId);
                        }
                    }
                }
                result = true;
            }
            catch (Exception exc)
            {
                string mess = exc.Message;
            }
            return result;
        }

        //OK1
        private void InsertMember(int groupID, int memberId, DateTime datetime)
        {
            try
            {
                groupMemberRow = groupMemberTbl.Newtm_group_memberRow();
                groupMemberRow.groupId = groupID;
                groupMemberRow.memberId = memberId;
                groupMemberRow.createOn = datetime;
                groupMemberTbl.Addtm_group_memberRow(groupMemberRow);
                groupMemberTA.Update(groupMemberTbl);
            }
            catch (Exception exc)
            {
                string mess = exc.Message;
            }
        }

        //OK1
        private bool InsertSelectedMembers()
        {
            bool result = false;
            try
            {
                ArrayList arSelectedNodes = tm_GroupList_MemberList.GetSelectedNodesArray();

                if (arSelectedNodes != null)
                {
                    for (int idx = 0; idx < arSelectedNodes.Count; idx++)
                    {
                        for (int memberIdx = 0; memberIdx < gvMemberList.Rows.Count; memberIdx++)
                        {
                            CheckBox ck = (CheckBox)gvMemberList.Rows[memberIdx].FindControl("ckMember");
                            if (ck.Checked)
                            {
                                Label lblUserId = (Label)gvMemberList.Rows[memberIdx].FindControl("lblUserId");
                                InsertMember(int.Parse(arSelectedNodes[idx].ToString()), int.Parse(lblUserId.Text), DateTime.Now);
                            }
                        }
                    }
                    result = true;
                }
            }
            catch (Exception exc)
            {
                string mess = exc.Message;
                result = false;
            }
            return result;
        }

        //OK1
        private bool ValidateHasSelectedGroup()
        {
            for (int i = 0; i < gvGroupList.Rows.Count; i++)
            {
                CheckBox ck = (CheckBox)gvGroupList.Rows[i].FindControl("ck");
                if (ck.Checked)
                    return true;
            }
            return false;
        }

        //OK1
        private bool ValidateHasSelectGroup()
        {
            ArrayList arGroup = new ArrayList();

            arGroup = tm_GroupList_MemberList.GetSelectedNodesArray();

            if (arGroup != null && arGroup.Count > 0)
                return true;

            return false;
        }
   
        //OK1
        protected void btnAddGroupSave_Click(object sender, EventArgs e)
        {
            if (ValidateAddGroup())
                if (AddGroup())
                    sysLibs.ShowNotice(lblMessage, "Thêm nhóm mới thành công", false);
                else
                    sysLibs.ShowNotice(lblMessage, "Thêm nhóm mới không thành công", true);
        }

        //OK1
        protected void ckMemberList_SelectedAll_CheckedChanged(object sender, EventArgs e)
        {
            Common.sysLibs.ToggleCheckState(gvMemberList, "ckMember", chkCheckAllMember.Checked);
        }

        //OK1
        protected void btnMemberList_Add_Click(object sender, EventArgs e)
        {
            if (ValidateHasSelectedMember())
                if (ValidateHasSelectGroup())
                    if (InsertSelectedMembers())
                        sysLibs.ShowNotice(lblAddMemberMes, "Thêm thành viên vào nhóm thành công", false);
                    else
                        sysLibs.ShowNotice(lblAddMemberMes, "Thêm thành viên vào nhóm không thành công", true);
                else
                    sysLibs.ShowNotice(lblAddMemberMes, "Chọn nhóm", true);
            else
                sysLibs.ShowNotice(lblAddMemberMes, "Chọn thành viên", true);
        }
       
        //OK1
        protected void btnAddGroupCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(TabId,"group","mid="+ModuleId));
        }

        //OK1
        protected void btnMemberList_Cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(TabId));
        }
     
        //OK1
        protected void gvMemberList_DataBound(object sender, EventArgs e)
        {
            pnlMemberList.Visible = gvMemberList.Rows.Count > 0;
            pnlAddToGroup.Visible = gvMemberList.Rows.Count > 0;
        }

        //OK1
        protected void btnReset_Click(object sender, EventArgs e)
        {
            tbxGroupName.Text = "";
            cbxGroupName.Checked = false;
            tbxDescription.Text = "";
            ddlGroupTypeS.SelectedIndex = 0;
        }

        //OK1
        protected void btnMemberList_Member_Click1(object sender, EventArgs e)
        {
            pnlAddToGroup.Visible = false;
            pnlMemberList.Visible = false;
            SearchGroup();
        }

        //OK1
        protected void gvGroupList_DataBound(object sender, EventArgs e)
        {
            cbxCheckAll.Visible = gvGroupList.Rows.Count > 0;
            btnDeleteGroup.Visible = cbxCheckAll.Visible;
        }

        //OK1
        protected void gvGroupList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvGroupList.PageIndex = e.NewPageIndex;
            SearchGroup();
        }

        //OK1
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            pnlAddGroup.Visible = true;
            pnlSearchGroup.Visible = false;
            pnlAddToGroup.Visible = false;
            pnlMemberList.Visible = false;
        }

        //OK1
        protected string GetURL(string groupId)
        {
            string URL = DotNetNuke.Common.Globals.NavigateURL(TabId, "group", "mid=" + ModuleId, "groupId=" + int.Parse(groupId));
            return URL;
        }

        //OK1
        private string GetGroupNameByGroupId(int groupId)
        {
            userGroupTbl = userGroupTA.GetDataByGroupId(groupId);
            return userGroupTbl.Rows[0]["groupCode"].ToString().Trim();
        }

        //OK1
        private void GetMemberByGroup(int groupId)
        {
            try
            {
                SearchGroup();
                lblGroupName.Text = GetGroupNameByGroupId(groupId);
                pnlMemberList.Visible = true;
                string strQuery = BuiltGetMemberByGroupQueryString(groupId);
                dtsMemberList.ConnectionString = sysLibs.GetConnectionString;
                dtsMemberList.SelectCommand = strQuery;
                dtsMemberList.Select(DataSourceSelectArguments.Empty);
                gvMemberList.DataBind();
            }
            catch (Exception exc)
            {
                string mess = exc.Message;
            }
        }

        //OK1
        private string BuiltGetMemberByGroupQueryString(int groupId)
        {
            string SQLCmd = "";
            try
            {
                SQLCmd += " SELECT b.account, a.createOn, a.id,b.userId, " +
                          " CASE WHEN b.userType & " + sysLibs.turnBitOn(0, consts.constENTBitPos) + ">0" +
                          " THEN b.companyName1 ELSE b.fullName END AS name1 " +
                          " FROM tm_group_member a INNER JOIN tm_users b ON a.memberId = b.userId " +
                          "                        INNER JOIN tm_user_groups c ON a.groupId = c.groupId " +
                          " WHERE a.groupId = " + groupId;
            }
            catch (Exception exc)
            {
                string mess = exc.Message;
            }
            return SQLCmd;
        }

        //OK1
        protected string getEnterpriseURL(string userId)
        {
            string URL = "";
            int myUserId = 0;
            int.TryParse(userId, out myUserId);
            int tabId = appLibs.GetTabIdByName(PortalId, "enterprise");
            int moduleId = appLibs.GetModuleIdByName(PortalId, "enterprise");
            URL = DotNetNuke.Common.Globals.NavigateURL(tabId, "viewdetail", "mid=" + moduleId, "userId=" + myUserId);
            return URL;
        }

        //OK1
        protected void gvGroupList_Sorting(object sender, GridViewSortEventArgs e)
        {
            SearchGroup();
        }

        //OK1
        private bool ValidateHasSelectedMember()
        {
            for (int i = 0; i < gvMemberList.Rows.Count; i++)
            {
                CheckBox ck = (CheckBox)gvMemberList.Rows[i].FindControl("ckMember");
                if (ck.Checked)
                    return true;
            }
            return false;
        }

        //OK1
        protected void cbxCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            Common.sysLibs.ToggleCheckState(gvGroupList, "ck", cbxCheckAll.Checked);
        }

        //OK1
        protected void btnDeleteGroup_Click(object sender, EventArgs e)
        {
            if (ValidateHasSelectedGroup())
                if (DeleteSelectedGroups())
                {
                    SearchGroup();
                    sysLibs.ShowNotice(lblMessage, "Xóa nhóm thành công", false);
                }
                else
                    sysLibs.ShowNotice(lblMessage, "Xóa nhóm không thành công", true);
            else
                sysLibs.ShowNotice(lblMessage, "Chọn nhóm", true);
        }

        //OK1
        protected void btnDeleteMember_Click(object sender, EventArgs e)
        {
            if (ValidateHasSelectedMember())
                if (DeleteSelectedMembers())
                {
                    GetMemberByGroup(myGroupId);
                    sysLibs.ShowNotice(lblMessage, "Xóa thành viên thành công", false);
                }
                else
                    sysLibs.ShowNotice(lblMessage, "Xóa thành viên không thành công", true);
            else
                sysLibs.ShowNotice(lblMessage, "Chọn thành viên", true);
        }

        //OK1
        private bool DeleteSelectedMembers()
        {
            bool result = false;
            try
            {
                for (int i = 0; i < gvMemberList.Rows.Count; i++)
                {
                    CheckBox ck = (CheckBox)gvMemberList.Rows[i].FindControl("ckMember");
                    if (ck.Checked)
                    {
                        Label lblID = (Label)gvMemberList.Rows[i].FindControl("lblID");
                        groupMemberTA.Delete(int.Parse(lblID.Text));
                    }
                }
                result = true;
            }
            catch (Exception exc)
            {
                string mess = exc.Message;
            }
            return result;
        }

        //OK1
        protected void gvMemberList_Sorting(object sender, GridViewSortEventArgs e)
        {
            GetMemberByGroup(myGroupId);
        }
}
}

